require('script!jquery');
require('infinite-scroll');
require('imports?jQuery=jquery!jquery-pin/jquery.pin');
var Masonry = require('masonry');
var imagesLoaded = require('imagesloaded');

var ms;
jQuery(function($) {
	init();
	plugins();
})

function loading(text,autoClose){
	var autoClose = autoClose || 0
	var loadingContainer = $('#infscr-loading');
	loadingContainer.find('.text').text(text);
	loadingContainer.show();
	if(autoClose){
		setTimeout(function(){
			loadingContainer.hide();
		},2000);
	}
	
}

function init() {
	$('.paginate .more .next').on('click', function(e) {
		$('#masonry-1').infinitescroll('retrieve');
		loading('数据加载中······');
		return false;
	})
	$('ul.menu').append('<li class="search"><span class="iconfont icon-search"></span></li>')
}

function showListMosaic() {
	/* MOSAIC 1 */
	var container1 = $('#masonry-1')[0];
	// setTimeout(function() {
	if(container1){
		ms = new Masonry(container1, {
			itemSelector: 'li'
		})
		// }, 600);
		$('.paginate').show();
	}
}

function infinite_scroll() {
	var container = $('#masonry-1');
	container.infinitescroll({
		navSelector: '.paginate',
		nextSelector: '.paginate ul li.next a',
		itemSelector: '#masonry-1 li.col',
		errorCallback:function(){
			$('.paginate').hide();
			loading('加载数据出错!',1);

		}
	}, function(newElements1) {
		// var $newElems1 = $(newElements1).css({
		// 	opacity: 0
		// });
		console.log(newElements1);
		try{
			ms.appended(newElements1);
		}catch(e){
			showListMosaic()
		}
		
		showListMosaic();
		setTimeout(showListMosaic,2000);
		
		var current = $('.paginate ul li a.active').parent().next();
		var nextHref = current.next().find('a').attr('href');
		$('.paginate ul li a.active').removeClass('active');
		current.find('a').addClass('active');
		$('.paginate ul .next a').attr('href',nextHref);
		loading('数据加载成功',1)

	})
	$(window).unbind('.infscr');
	$('nav.main').pin({
		containerSelector: "body"
	})
}

function plugins() {
	$(window).on('resize', showListMosaic);
	$('.rollover img').on('click',showListMosaic);
	window.onload = showListMosaic;
	setTimeout(showListMosaic,2000);
	infinite_scroll();
	$('nav.main').pin({
		containerSelector: "body"
	})
	$('ul.menu').on('click','.search',function(e){
		$('.search-text').css({
			visibility:'visible',
			opacity:1
		}).find('input.text').focus();
		return false;
	})
	$('#content').on('click',function(e){
		$('.search-text').css({
			visibility:'hidden',
			opacity:0
		});
	})
}
